package utilities;


import java.io.*;
import java.util.*;
import java.lang.reflect.*;
import edu.cmu.sphinx.frontend.util.Microphone;
import edu.cmu.sphinx.recognizer.Recognizer;
import edu.cmu.sphinx.result.Result;
import edu.cmu.sphinx.util.props.ConfigurationManager;


public class VoiceEngine extends Engine {

	private static boolean active = true;
	private Recognizer recognizer;
	public VoiceEngine()
	{
	}
	
	public VoiceEngine(String name, BufferedWriter log, List actionList,
			Object configData, int sleeps, EngineCommander commander) {

		
		super(name, log, actionList, configData, sleeps, commander);
	}
	
	public void queueVoice(String heardVoice)
	{
		servers.Dragon.voiceDelegator(heardVoice);
	}
	public void close() 
	{
		this.active=false;

		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//recognizer.deallocate();
		
		try {
			log.write(" stopped\n");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}	
		try {
			log.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	public void run()
	{
		try
		{
	    ConfigurationManager cm;
	    //log.write("loading config\n"); 
	    
	    
	  //  cm = new ConfigurationManager(VoiceEngine.class.getResource("/workspace/helloworld/bin/helloworld/helloworld.config.xml"));
	    cm = new ConfigurationManager("C:\\temp\\dragon\\voice\\dragonVoice.config.xml");
	    	    
	    log.write("loaded config\n"); 
	    recognizer = (Recognizer) cm.lookup("recognizer");
	    recognizer.allocate();
	
	    // start the microphone or exit if the programm if this is not possible
	    Microphone microphone = (Microphone) cm.lookup("microphone");

	    if (!microphone.startRecording()) {
	        try {
				log.write("Cannot start microphone.");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        recognizer.deallocate();
	        return;
	    }
	
	    // loop the recognition until the programm exits.
	    while (active) {

	        Result result = recognizer.recognize();
	
	        if (result != null) {
	            String resultText = result.getBestFinalResultNoFiller();
	            System.out.println("You said: " + resultText + '\n');
	            
	            if (debug>0) log.write(resultText + "\n");
	            
	            queueVoice(resultText);
	            
	        } 
	    }
		}catch (Exception e)
		{
			try {
				
				//log.write("Thread bombed " + e.getMessage() + "\n");
				//e.printStackTrace(new PrintWriter(log));
				e.printStackTrace();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		recognizer.deallocate();
	}
	
	
}
